#include "common.h"

#define LOG_PATH    "log"
#define LOG_PREFIX  "/usr/home/zhangqiang3/my_nginx/"

int Init_Log(Server *server)
{
    
    u_char  *p, *name, *prefix, *logname;
    size_t   nlen, plen;

    logname = (u_char *) LOG_PATH;
    nlen = strlen(logname);
    prefix = (u_char *)LOG_PREFIX;
    plen = strlen(prefix);

    p = NULL;
    if (plen) {
        name = DS_Pcalloc(server->pool, plen + nlen + 1);
        if (name == NULL) {
            return -1;
        }
        p = memcpy(name, prefix, plen);
        p += plen;
        p = memcpy(p, logname, nlen);
        p += nlen + 1;
        *p = '\0';
        p = name;
    }
    
    server->log->fd = open((const char *) name, O_CREAT|O_WRONLY|O_APPEND, 0644);

    if (server->log->fd == -1) {
        server->log->fd = STDERR_FILENO;
        write(server->log->fd, "Open Log File Faild\n", 20);
        return -1;
    }

    return 0;
}

void Log_Write(Log *log, const char *fmt, ...)
{
    va_list  args;
    int len;
    u_char   errstr[1024] = {0};

    if (log->fd == -1) {
        return;
    }

    va_start(args, fmt);
    len = vsnprintf(errstr, sizeof(errstr), fmt, args);
    va_end(args);

    if (len == 1024) {
        len--;
    }
    errstr[len] = '\n';
    write(log->fd, errstr, len + 1);

}

void Log_Write_Stderr(const char *fmt, ...)
{
    va_list  args;
    int len;
    u_char   errstr[1024] = {0};

    va_start(args, fmt);
    len = vsnprintf(errstr, sizeof(errstr), fmt, args);
    va_end(args);

    if (len == 1024) {
        len--;
    }
    errstr[len] = '\n';
    write(STDERR_FILENO, errstr, len + 1);

}

